""" 日志操作
@Project: Rebar
@File: log_mapper.py
@Author: hzc
@Date: 2023/3/29 10:15
"""
import json
from starlette.requests import Request
from model.db import reservoir_sensitivity
from model.db.user_model import TbLog
from model.db import reservoir_sensitivity

def add_log(request: Request, error_info):
    """
    向数据库添加日志记录
    :param request:
    :param error_info:
    :return:
    """
    try:
        log = TbLog(
            client=request.scope["client"][0],
            method=request.scope["method"],
            path=request.scope["path"],
            query_params=request.scope.get("query_string"),
            path_params=json.dumps(request.scope.get("path_params")),
            error_info=error_info,
        )
        reservoir_sensitivity.add(log)
        reservoir_sensitivity.commit()
        reservoir_sensitivity.refresh(log)
    except Exception as e:
        print("log_mapper.py", e, e.__traceback__.tb_lineno)
        reservoir_sensitivity.rollback()
